/*
 * 广告活动管理
 * @date 2016/6/21
 */

window.onload = function () {
    // 点击查看图片地址
    $('.table').delegate('td.order-node', 'click', function () {
        var path = $(this).attr('path') + '?' + Math.random();
//        var type = $(this).attr('type');
//        var w = '', h='';
//        if(type == 'app') {
//            w = '600px';
//            h = '780px';
//        } else {
//            w = '750px';
//            h = '240px';
//        }
        var nodeContent = '<img style="display:block;width:100%;height:100%" src="' + path + '" alt="" title="" id="">';
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['250px', '250px'], //宽高
            closeBtn: 0, //不显示关闭按钮
            shadeClose: true, //开启遮罩关闭
            content: nodeContent,
            success: function (layero, index) {
            }
        });
    });

    // 点击添加按钮
    $('.search-inline').delegate('#add', 'click', function () {
        var index = layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            maxmin: false,
            content: '/adadd/add',
            success: function (layero, index) {
                initAddPanel(layero, index);
            }
        });
        layer.full(index);
    });

    // 点击修改优惠券
    $(".table").delegate(".modify", "click", function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var id = Number($(this).parent().siblings('#id').text());
        console.log(id);
        var index = layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            maxmin: false,
            content: '/admodify/modify',
            success: function (layero, index) {
                initModifyCoupon(layero, id);
            }
        });
        layer.full(index);
    });

    // 点击启用优惠券
    $(".table").delegate(".start", "click", function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var id = Number($(this).parent().siblings('#id').text());
        console.log(id);
        layer.confirm("确定启用此活动吗？", {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            setStatus(id, 1);
            list();
            layer.close(index);
        });
    });

    // 点击停用优惠券
    $(".table").delegate(".stop", "click", function () {
        if ($(this).hasClass("invalid")) {
            return;
        }
        var id = Number($(this).parent().siblings('#id').text());
        console.log(id);
        layer.confirm("确认停用？停用后不可再次启用", {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            setStatus(id, 3);
            list();
            layer.close(index);
        });
    });
};

//列表每页显示条数
var perPage = 10;

//是否请求完成标识
var loadBool = true;

// 页面初始化
$(function () {
    list();
});

// 查询推广活动
$(document).delegate("#query", "click", function () {
    list();
});

// 清空
$(document).delegate("#clear", "click", function () {
    $("#astatus").val('-1');
    $("#name").val('');
    $("#type").val('-1');
    $("#cities").val('');
    $("#start_time").val('');
    $("#end_time").val('');
    $("#list").empty();
    list();
});

function list() {
    $("#curPage").text(0);
    $("#pages").text(0);
    getAdList(1);
}

//下一页
$(document).delegate("#nextPage", "click", function () {
    var curPage = Number($("#curPage").text());
    var pages = Number($("#pages").text());
    if (curPage == pages) {
        return;
    }
    getAdList(curPage + 1);
});

//上一页
$(document).delegate("#lastPage", "click", function () {
    var curPage = Number($("#curPage").text());
    if (curPage <= 1) {
        return;
    }
    getAdList(curPage - 1);
});

//获取推广活动列表
function getAdList(curPage) {
    if (!loadBool) {
        return;
    }
    loadBool = false;
    $("#list").empty();
    //loading层
    var layerIndex = layer.load(2, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });

    var index = curPage - 1;
    var params = JSON.stringify({
        "astatus": Number($("#astatus option:selected").val()),
        "name": $("#name").val(),
        "type": Number($("#type option:selected").val()),
        "cities": $("#cities").val(),
        "start_time": $("#start_time").val(),
        "end_time": $("#end_time").val(),
        'pos': index * perPage,
        'limit': perPage
    });
    console.log(params);
    $.ajax({
        type: "POST",
        url: "/admanager/glist",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            layer.close(layerIndex);
            if (data.status == 0) {
                $("#pages").text(Math.ceil(data.count / perPage));
                if (data.data.length > 0) {
                    $("#curPage").text(index + 1);
                    for (var i = 0; i < data.data.length; i++) {
                        var ad = data.data[i];
                        var astatus = '';
                        var opt = '';
                        switch (ad.astatus) {
                            case 0:
                                astatus = '未开始';
                                opt = '<a class="modify" href="javascript:void(0);" title="">修改</a><a class="start" href="javascript:void(0);" title="">启用</a><a class="stop" href="javascript:void(0);" title="">停用</a>';
                                break;
                            case 1:
                                astatus = '正常';
                                opt = '<a class="modify invalid" href="javascript:void(0);" title="">修改</a><a class="start invalid" href="javascript:void(0);" title="">启用</a><a class="stop" href="javascript:void(0);" title="">停用</a>';
                                break;
                            case 2:
                                astatus = '过期';
                                opt = '<a class="modify invalid" href="javascript:void(0);" title="">修改</a><a class="start invalid" href="javascript:void(0);" title="">启用</a><a class="stop invalid" href="javascript:void(0);" title="">停用</a>';
                                break;
                            case 3:
                                astatus = '已停止';
                                opt = '<a class="modify invalid" href="javascript:void(0);" title="">修改</a><a class="start invalid" href="javascript:void(0);" title="">启用</a><a class="stop invalid" href="javascript:void(0);" title="">停用</a>';
                                break;
                        }
                        var type = '';
                        switch (ad.type) {
                            case 0:
                                type = '其他';
                                break;
                            case 1:
                                type = '推广';
                                break;
                            case 2:
                                type = '营销';
                                break;
                            case 3:
                                type = '广告';
                                break;
                        }
                        var citiies = '';
                        if (ad.cities) {
                            for (var j = 0; j < ad.cities.length; j++) {
                                if (ad.cities[j] == '*') {
                                    citiies = '全国,';
                                    break;
                                }
                                citiies += ad.cities[j] + ',<br>';
                            }
                        } else {
                            citiies = '全国,';
                        }

                        var row = "<tr>" +
                                "<td id='id'>" + ad.id + "</td>" +
                                "<td>" + ad.act_no + "</td>" +
                                "<td>" + ad.name + "</td>" +
                                "<td>" + ad.start_time + '---' + ad.end_time + "</td>" +
                                "<td>" + citiies + "</td>" +
                                "<td>" + type + "</td>" +
                                "<td>" + astatus + "</td>" +
                                "<td>" + ad.popup_interval + "</td>" +
                                "<td>" + ad.gateway + "</td>";
                        if (!ad.poster) {
                            row += "<td></td>";
                        } else {
                            row += "<td class='order-node' path='" + ad.poster + "' type='app'>" + '是' + "</td>";
                        }
                        if (!ad.wechat_poster) {
                            row += "<td></td>";
                        } else {
                            row += "<td class='order-node' path='" + ad.wechat_poster + "' type='wechat'>" + '是' + "</td>";
                        }
                        row += "<td>" + opt + "</td>" + "</tr>";
                        $("#list").append(row);
                    }
                }
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
            loadBool = true;
        },
        error: function () {
            layer.close(layerIndex);
            bbx_alert_error("出错啦~");
            loadBool = true;
        }
    });
}

function initAddPanel(layero, index) {
    var layerIframe = layero.find('iframe:first-child').contents();
    back(layerIframe);
    addAct(layerIframe);
}

// 返回上一页
function back(elem) {
    elem.on('click', "#back", function () {
        layer.closeAll();
        list();
    });
}

//添加推广活动
function addAct(elem) {
    elem.find("#add").on("click", function () {
        if (!checkParam(elem)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var params = createParam(elem);
        var layerIndex = layer.msg('新增中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/admanager/add",
            contentType: "application/json",
            dataType: "json",
            data: params,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error("出错啦~");
            }
        });
    });
}

//检查参数
function checkParam(elem) {
    var rightParam = true;

    elem.find("#act_no").val() ? elem.find("#act_nomark").text('') : (elem.find("#act_nomark").text('请生成活动编号！'), rightParam = false);
    if (elem.find("#name").val()) {
        elem.find("#namemark").text('');
        if (elem.find("#name").val().length > 50) {
            elem.find("#nameremark").addClass('mandatory');
            rightParam = false;
        }
    } else {
        elem.find("#namemark").text('请填写！');
        rightParam = false;
    }
    elem.find("#start_time").val() && elem.find("#end_time").val() ? elem.find("#endtimemark").text('') : (elem.find("#endtimemark").text('请填写！'), rightParam = false);
    elem.find("#popup_interval").val() ? elem.find("#popup_intervalmark").text('') : (elem.find("#popup_intervalmark").text('请填写！'), rightParam = false);
    elem.find("#appImgName").text() ? (elem.find("#appImgRemark").text('有选择的图片待处理!'), rightParam = false) : elem.find("#appImgRemark").text('');
    elem.find("#wechatImgName").text() ? (elem.find("#wechatImgRemark").text('有选择的图片待处理!'), rightParam = false) : elem.find("#wechatImgRemark").text('');
    if (elem.find('#citiesPart').attr("checked")) {
        var count = elem.find("#citiesSelect option").length;
        count > 0 ? elem.find("#citiesmark").text('') : (elem.find("#citiesmark").text('请填写！'), rightParam = false);
    }
    if (elem.find("#description").val().length > 200) {
        elem.find("#descriptionmark").addClass('mandatory');
        rightParam = false;
    }

    return rightParam;
}

//创建参数
function createParam(elem, id) {
    var cities = [];
    if (elem.find('#citiesPart').attr("checked")) {
        var count = elem.find("#citiesSelect option").length;
        for (var i = 0; i < count; i++) {
            var text = elem.find("#citiesSelect").get(0).options[i].text;
            cities.push(text);
        }
    } else {
        cities.push('*');
    }
    var param = JSON.stringify({
        'id': id ? id : 0,
        'act_no': elem.find('#act_no').val(),
        'name': elem.find('#name').val(),
        'start_time': elem.find('#start_time').val(),
        'end_time': elem.find('#end_time').val(),
        'type': Number(elem.find('#type option:selected').val()),
        'astatus': Number(elem.find('#astatus option:selected').val()),
        'gateway': elem.find('#gateway').val(),
        'poster': elem.find('#poster').attr('src').substr(0, elem.find('#poster').attr('src').lastIndexOf('?')),
        'description': elem.find('#description').val(),
        'cities': cities,
        'popup_interval': Number(elem.find("#popup_interval").val()),
        'status': 0,
        'rank': 1,
        'wechat_poster': elem.find('#wechat_poster').attr('src').substr(0, elem.find('#wechat_poster').attr('src').lastIndexOf('?'))
    });
    console.log(param);
    return param;
}

function initModifyCoupon(layero, id) {
    var layerIframe = layero.find('iframe:first-child').contents();
    back(layerIframe);
    fillDetail(layerIframe, id);
    modifyAct(layerIframe, id);
}

//填充活动详情
function fillDetail(elem, id) {
    var params = JSON.stringify({'id': id});
    $.ajax({
        type: "POST",
        url: "/admanager/gdetail",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                _fillDetail(elem, data.info);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}

function _fillDetail(elem, data) {
    elem.find('#act_no').val(data.act_no);
    elem.find('#name').val(data.name);
    setNum(elem.find('#name'), 50, elem.find('#nameNum'), elem.find('#nameNum1'), elem.find('#nameremark'));
    elem.find('#start_time').val(data.start_time);
    elem.find('#end_time').val(data.end_time);
    elem.find("#type option[value='" + data.type + "']").attr("selected", true);
    elem.find("#astatus option[value='" + data.astatus + "']").attr("selected", true);
    elem.find('#gateway').val(data.gateway);
    elem.find('#popup_interval').val(data.popup_interval);
    if (data.poster) {
        elem.find('#appImgMark').hide();
        elem.find('#poster').attr('src', data.poster + '?' + Math.random());
    }
    if (data.wechat_poster) {
        elem.find('#wechatImgMark').hide();
        elem.find('#wechat_poster').attr('src', data.wechat_poster + '?' + Math.random());
    }
    elem.find('#description').val(data.description);
    setNum(elem.find('#description'), 200, elem.find('#descriptionNum'), elem.find('#descriptionNum1'), elem.find('#descriptionmark'));
    var options = '';
    if (data.cities) {
        for (var i = 0; i < data.cities.length; i++) {
            if (data.cities[i] == '*') {
                elem.find('#citiesAll').attr('checked', true);
                break;
            }
            options += "<option value=''>" + data.cities[i] + "</option>";

        }
        if (options) {
            elem.find('#citiesPart').attr('checked', true);
            elem.find('.cities-model').removeClass('display-none');
            elem.find('#citiesSelect').append(options);
        }
    } else {
        elem.find('#citiesAll').attr('checked', true);
    }
}

//修改推广活动
function modifyAct(elem, id) {
    elem.find("#modify").on("click", function () {
        if (!checkParam(elem)) {
            layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
            return;
        }
        var params = createParam(elem, id);
        var layerIndex = layer.msg('修改中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
        $.ajax({
            type: "POST",
            url: "/admanager/modify",
            contentType: "application/json",
            dataType: "json",
            data: params,
            success: function (data) {
                layer.close(layerIndex); //关闭加载层
                if (data.status == 0) {
                    layer.msg('修改成功！', {icon: 1, time: 1000}, function () {
                        layer.closeAll();
                        list();
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error("出错啦~");
            }
        });
    });
}

//修改推广活动状态
function setStatus(id, astatus) {
    var params = JSON.stringify({
        'id': id,
        'astatus': astatus
    });
    $.ajax({
        type: "POST",
        url: "/admanager/setStatus",
        contentType: "application/json",
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.status == 0) {
                layer.msg('设置状态成功！', {icon: 1, time: 1000}, function () {
                    layer.closeAll();
                    list();
                });
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            bbx_alert_error("出错啦~");
        }
    });
}